<?php

namespace app\common\model\worker;

use app\common\model\AdminModel;
use app\common\model\BaseModel;
use app\common\model\node\NodeModel;
use app\common\model\node\NodeProcessModel;
use app\common\model\sale\SaleAfterDetailModel;
use app\common\model\sale\SaleAfterModel;
use helper\FormBuilder;
use think\facade\Db;


class TaskModel extends BaseModel
{
    protected $table = 'task';

    private function getStatusText($info){
      $statusText = '';
      if($info['is_receive']==0) $statusText='待接受';
      if($info['is_receive']==1 && $info['is_submit']==0) $statusText='待执行';
      if($info['is_submit']==1 && $info['is_audit']==0) $statusText='已完成';
      if($info['is_submit']==1 && $info['is_audit']==1 && $info['audit_status']==0) $statusText='待审核';
      if($info['is_submit']==1 && $info['is_audit']==1 && $info['audit_status']==1) $statusText='已审核';
      if($info['is_audit']==1 && $info['audit_status']==-1) $statusText='审核驳回';
      return $statusText;
    }


    public function _formatList($list){
        $customerIds = array_column($list,'customer_id');
        $orderIds = array_column($list,'order_id');
        $customerModel = new CustomerModel();
        $customerList = $customerModel->where('id','in',$customerIds)->column('*','id');
        $adminList = AdminModel::column('*','id');
        foreach ($list as $k=>$v){
            $v['customer_info'] = $customerList[$v['customer_id']] ?? [];
            $v['send_nickname'] = $adminList[$v['admin_id']]['nickname'] ?? '';
            $v['receive_nickname'] = $adminList[$v['receive_admin_id']]['nickname'] ?? '';
            $v['audit_nickname'] = $adminList[$v['audit_admin_id']]['nickname'] ?? '';
            $content = empty($v['process_content'])?[]:json_decode($v['process_content'],true);
            if(!empty($content)){
                $content = $this->getContent($content);
            }
            $v['process_content'] = $content;
            $v['task_status_text'] = $this->getStatusText($v);
            $list[$k] = $v;
        }
        return $list;
    }

    /**
     * 获取任务详情
     */
    public function getInfo($id){
        $adminList = AdminModel::column('*','id');
        $info = $this->where('id',$id)->find();
        $content = empty($info['process_content'])?[]:json_decode($info['process_content'],true);
        if(!empty($content)){
            $content = $this->getContent($content);
        }
        $info['task_imgs'] = empty($info['task_imgs'])?[]:json_decode($info['task_imgs'],true);
        $info['task_file'] = empty($info['task_file'])?[]:json_decode($info['task_file'],true);
        $info['task_status_text'] = $this->getStatusText($info);
        $info['process_content'] = $content;
        $info['customer_info'] = CustomerModel::where('id',$info['customer_id'])->find();
        $info['send_nickname'] = $adminList[$info['admin_id']]['nickname'] ?? '';
        $info['receive_nickname'] = $adminList[$info['receive_admin_id']]['nickname'] ?? '';
        $info['audit_nickname'] = $adminList[$info['audit_admin_id']]['nickname'] ?? '';
        $info['audit_nicknames'] = '';
        $info['copy_nicknames'] = '';
        if(!empty($info['audit_admin_ids'])){
            $nicknames = AdminModel::where('id','in',$info['audit_admin_ids'])->column('nickname');
            $info['audit_nicknames'] = implode(',',$nicknames);
        }
        if(!empty($info['copy_admin_ids'])){
            $nicknames = AdminModel::where('id','in',$info['copy_admin_ids'])->column('nickname');
            $info['copy_nicknames'] = implode(',',$nicknames);
        }
        $info['node_process'] = NodeProcessModel::where('node_id','=',$info['node_id'])->order('show_order asc')->select()->toArray();
        $nodeModel = new NodeModel();
        $info['node_list'] = $nodeModel->getNodeList($info['node_type']);
        return $info;
    }

    /**
     * 获取任务表单内容
     */
    private function getContent($content){
        foreach($content as $k=>$v){
            if(!empty($v['content'])){
                switch ($v['input_type']){
                    case '_text':
                        $showHtml = '<div class="input-text">'.$v['content'].'</div>';
                        break;
                    case '_number':
                        $showHtml = '<div class="input-number">'.$v['content'].'</div>';
                        break;
                    case '_textarea':
                        $showHtml = '<div class="input-textarea">'.$v['content'].'</div>';
                        break;
                    case '_uploadImages':
                        if(!is_array($v['content'])){
                            $imgs = explode(',',$v['content']);
                            $v['content'] = $imgs;
                        }
                        $showHtml = '<div class="input-images" data-group="'.json_encode($v['content']).'">';
                        foreach ($v['content'] as $img){
                            $img = str_replace("https://warning-file.180wx.cn","http://chuchu.chaiyun2617.cn",$img);
                            $showHtml.='<div class="item" data-src="'.$img.'" style="background-image:url('.$img.')"></div>';
                        }
                        $showHtml.='</div>';
                        break;
                   /* case '_uploadFiles':
                        $files = explode(',',$v['content']);
                        $v['content'] = $files;
                        $showHtml = '<div class="input-images">';
                        foreach ($files as $file){
                            $showHtml.='<a class="item" src="'.$file['file_url'].'">'.$file['file_name'].'</a>';
                        }
                        $showHtml.='</div>';
                        break;*/
                }
                $v['show_html'] = $showHtml;
            }
            $content[$k] = $v;
        }
        return $content;
    }

    /**
     * 获取任务的节点步骤详情
     * @param $id
     * @return array|Db|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getProcessInfo($id){
        $info = $this->getInfo($id);
        $processInfo = Db::view('node_process', '*')
            ->view('node', 'node_type,node_name,success_process_status', 'node_process.node_id=node.id')
            ->where('node_process.id', '=', $info['process_id'])
            ->find();
        $processConfig = empty($processInfo['process_config'])?[]:json_decode($processInfo['process_config'],true);
        $processInfo['node_notice'] = empty($processInfo['node_notice'])?[]:explode("\r\n",$processInfo['node_notice']);
        if(!empty($processConfig)){
            foreach($processConfig as $k=>$v){
                $objOptions = [];
                if($v['is_required']==1){
                    $objOptions['dataType'] = '*';
                }
                $_fun  = $v['input_type'];
                $v['html'] = FormBuilder::$_fun($v['field_label'],'',$objOptions);
                $processConfig[$k] = $v;
            }
        }
        $processInfo['process_config'] =   $processConfig;
        $nextProcess =   NodeProcessModel::where('node_id',$processInfo['node_id'])
            ->where('show_order','>',$processInfo['show_order'])
            ->find();
        $processInfo['next'] = $nextProcess;
        $processInfo['task_info'] = $info;
        return $processInfo;
    }
    /**
     * 添加任务
     */
    public function addTask($customerId,$orderId=0,$nodeId,$processId,$receiveAdminId,$adminId,$action_table_id =''){
        $nodeInfo = Db::view('node_process', '*')
            ->view('node', 'node_type,node_name', 'node_process.node_id=node.id')
            ->where('node_process.id', '=', $processId)
            ->find();
        $map = [];
        $map[] = ['customer_id','=',$customerId];
        $map[] = ['order_id','=',$orderId];
        $map[] = ['node_id','=',$nodeId];
        $map[] = ['process_status','=',0];
        if($nodeInfo['node_type']==0){
            $map[] = ['receive_admin_id','=',$receiveAdminId];
        }


        $info = $this->where($map)->find();
        if(!empty($info)) exception('还有正在执行的'.$nodeInfo['node_name'].'任务，请先完成或取消后再发起');


        $map[] = ['process_id','=',$processId];
        $info = $this->where($map)->find();
        //todo 如果存在未完成的同客户或同订单的同步骤任务，更新任务执行人和审核人
        if(!empty($info)){
            if($info['receive_admin_id'] !=$nodeInfo['admin_id'] || $info['audit_admin_id'] !=$nodeInfo['audit_admin_id']){
                $info = self::update([
                    'receive_admin_id'=>$nodeInfo['admin_id'],
                    'audit_admin_id'=>$nodeInfo['audit_admin_id'],
                    'audit_admin_ids'=>$nodeInfo['audit_admin_id'],
                    'admin_id'=>$adminId,
                ]);
            }
        }else{
            $data  =[

                'customer_id'=>$customerId,
                'order_id'=>$orderId,
                'node_id'=>$nodeId,
                'node_type'=>$nodeInfo['node_type'],
                'node_name'=>$nodeInfo['node_name'],
                'process_id'=>$processId,
                'process_name'=>$nodeInfo['process_name'],
                'process_status'=>0,
                'receive_admin_id'=>$receiveAdminId ?? $nodeInfo['audit_admin_id'],//$receiveAdminId,
                'is_audit'=>$nodeInfo['is_audit'],
                'audit_admin_id'=>$receiveAdminId ?? $nodeInfo['audit_admin_id'],
                'audit_admin_ids'=>$receiveAdminId ?? $nodeInfo['audit_admin_id'],
                'admin_id'=>$adminId,
                'action_table_id' =>$action_table_id
            ];

            $info = self::create($data);
        }
        return $info;
    }

    public function addNewTask($customerId,$orderId=0,$nodeId,$processId,$receiveAdminId,$adminId,$action_table_id =''){
        $nodeInfo = Db::view('node_process', '*')
            ->view('node', 'node_type,node_name', 'node_process.node_id=node.id')
            ->where('node_process.id', '=', $processId)
            ->find();



            $data  =[

                'customer_id'=>$customerId,
                'order_id'=>$orderId,
                'node_id'=>$nodeId,
                'node_type'=>$nodeInfo['node_type'],
                'node_name'=>$nodeInfo['node_name'],
                'process_id'=>$processId,
                'process_name'=>$nodeInfo['process_name'],
                'process_status'=>0,
                'receive_admin_id'=>$receiveAdminId ?? $nodeInfo['audit_admin_id'],//$receiveAdminId,
                'is_audit'=>$nodeInfo['is_audit'],
                'audit_admin_id'=>$receiveAdminId ?? $nodeInfo['audit_admin_id'],
                'audit_admin_ids'=>$receiveAdminId ?? $nodeInfo['audit_admin_id'],
                'admin_id'=>$adminId,
                'action_table_id' =>$action_table_id,
                'copy_admin_ids' => 2,//抄送人
                'deadline_time' => date('Y-m-d H:i:s',strtotime('+1 day')) //截至时间， 当前时间加一天
            ];

            $info = self::create($data);

        return $info;
    }
    /**
     * 添加自定义任务
     * @param $data
     */
    public function addCustomTask($data,$adminId){
        $receiveIds = $data['receive_admin_ids'];
        if(strpos($receiveIds,',') !== false){
            $receiveIds = explode(',',$receiveIds);
        }else{
            $receiveIds = [$receiveIds];
        }
        foreach ($receiveIds as $k=>$v){
            $taskData[]=[
                'receive_admin_id'=>$v,
                'node_type'=>99,
                'node_name'=>$data['node_name'],
                'task_imgs'=>$data['task_imgs'],
                'task_file'=>$data['task_file'],
                'deadline_time'=>$data['deadline_time'],
                'audit_admin_ids'=>$data['audit_admin_ids'],
                'copy_admin_ids'=>$data['copy_admin_ids'],
                'admin_id'=>$adminId,
                'is_audit'=>1,
            ];
        }
        $info = self::insertAll($taskData);
        return $info;
    }

    /**
     * 提交任务表单
     * @param $data
     */
    public function submitTask($data,$adminId){
        $processInfo = $this->getProcessInfo($data['id']);
        $processConfig = $processInfo['process_config'];
        if(!empty($processConfig)){
            foreach($processConfig as $k=>$v){
               /* if($v['is_required']==1 && empty($data[$v['field_label']])){
                   exception($v['field_label'].'不能为空');
                }*/
                unset($v['html']);
                $v['content'] = $data[$v['field_label']];
                $processConfig[$k]=$v;
            }
        }
        $updateData = [
            'process_content'=>json_encode($processConfig,JSON_UNESCAPED_UNICODE),
            'is_submit'=>1,
            'submit_time'=>date('Y-m-d H:i:s'),
        ];
        //todo 不用审核的任务，更新任务状态 需要审核的任务不做其他操作
        if($processInfo['is_audit']==0){
            $updateData['process_status'] = $processInfo['process_status'];
        }
        $this->where('id',$data['id'])->update($updateData);
        //todo 是否最后一个步骤，不是最后的新增
        $info = $this->where('id',$data['id'])->find();
        if($processInfo['is_audit']==0 && !empty($processInfo['next'])){
            $this->addTask($info['customer_id'],$info['order_id'],$info['node_id'],$processInfo['next']['id'],$adminId,$info['receive_admin_id']);
        }
        //todo 执行任务回调
        $this->callBack($info,$processInfo);
        return $info;
    }

    /**
     * 审核任务
     * 通过审核执行下一步操作，未通过审核返回指定步骤
     * @param $data
     */
    public function auditTask($id,$adminId,$data){
        $info = $this->where('id',$id)->find();

        if($info['audit_admin_id']!=$adminId) exception('无审核权限');

        $processInfo = $this->getProcessInfo($id);
        $updateData = [
            'process_status'=>$processInfo['process_status'],
            'audit_admin_id'=>$adminId,
            'audit_status'=>1,
            'audit_idea'=>$data['audit_idea'],
            'audit_time'=>date('Y-m-d H:i:s'),
        ];
         $this->where('id',$id)->update($updateData);
        if(!empty($processInfo['next'])){
            $action_table_id = '';
            if($info['action_table_id']){
                $action_table_id = $info['action_table_id'];
                //指定客户代表
                if($info['node_id'] == 17 && $info['process_id'] == 28){
                    $orderInfo = OrderModel::where('id',$action_table_id)->find();
                    $customerGoodsData = CustomerGoodsDataModel::where('id',$orderInfo['goods_data_id'])->find();
                    $budget_id = CustomerBudgetModel::where('id',$customerGoodsData['budget_id'])->value('admin_id');
                    $processInfo['next']['audit_admin_id'] = $budget_id;//客户代表id
                }
                //尾单验收明细
                if($info['node_id'] == 19 && $info['process_id'] ==36){

                    $orderInfo = OrderModel::where('id',$action_table_id)->find();
                    OrderModel::where('id',$action_table_id)->update(['total_amount'=>$data['total_amount']]);
                    CustomerGoodsDataModel::where('id',$orderInfo['goods_data_id'])->update(['rectify_content'=>json_encode($data['rectify_content'],JSON_UNESCAPED_UNICODE)]);
                }
                $this->addNewTask($info['customer_id'],$info['order_id'],$info['node_id'],$processInfo['next']['id'],$processInfo['next']['audit_admin_id'],$adminId,$action_table_id);
            }else{
                $this->addTask($info['customer_id'],$info['order_id'],$info['node_id'],$processInfo['next']['id'],$info['audit_admin_id'],$adminId,$action_table_id);
            }


        }
        //美容审核经理通过进入下一步
        if($info['node_id'] == 20 && $info['process_id'] ==38){
            $action_table_id = $info['action_table_id'];
            $nodeProcess = NodeProcessModel::where('node_id', 22)->order('id', 'asc')->find();
            $this->addNewTask($info['customer_id'],$info['order_id'],$nodeProcess['node_id'],$nodeProcess['id'],$nodeProcess['audit_admin_id'],$adminId,$action_table_id);
        }
        //安装审核经理通过进入下一步
        if($info['node_id'] == 21 && $info['process_id'] ==42){
            $action_table_id = $info['action_table_id'];
            $nodeProcess = NodeProcessModel::where('node_id', 23)->order('id', 'asc')->find();
            $this->addNewTask($info['customer_id'],$info['order_id'],$nodeProcess['node_id'],$nodeProcess['id'],$nodeProcess['audit_admin_id'],$adminId,$action_table_id);
        }
        //todo 执行任务回调
        $this->callBack($info,$processInfo);
        return $info;
    }

    /**
     * 驳回审核
     * @param $id
     * @param $processId
     * @param $adminId
     */
    public function rejectTask($id,$processId,$auditIdea,$adminId,$task_imgs=''){
        $info = $this->where('id',$id)->find();
        if($info['audit_admin_id']!=$adminId) exception('无审核权限');
        $processInfo = $this->getProcessInfo($id);
        $updateData = [
            'process_status'=>$processInfo['process_status'],
            'audit_status'=>-1,
            'audit_admin_id'=>$adminId,
            'audit_idea'=>$auditIdea,
            'audit_time'=>date('Y-m-d H:i:s'),
            'task_imgs'=>$task_imgs
        ];
        $this->where('id',$id)->update($updateData);
        if(!$info['action_table_id']){
            $this->addTask($info['customer_id'],$info['order_id'],$info['node_id'],$processId,$adminId,$info['receive_admin_id']);
        }

        return $info;
    }

    /**
     * 撤回重做
     * @param $id
     */
    public function revokeTask($id,$adminId){
        $info = $this->where('id',$id)->find();
        if($info['is_audit']==1 && $info['audit_status']==1) exception('任务已审核，不能撤回');
        if($info['receive_admin_id'] !=$adminId) exception('无操作权限');
        $info = $this->where('id',$id)->update([
            'process_content'=>'',
            'is_submit'=>0,
            'submit_time'=>NULL,
        ]);
        return $info;
    }

    public function del($id){
        $info = $this->where('id',$id)->find();

        if($info['process_status']>0) exception('任务已执行，无法取消');
        $this->where('id',$id)->delete();
    }


    /**
     * 固定回调
     * @param $info
     * @param $processInfo
     */
    private function callBack($info,$processInfo){
        //var_dump($info->toArray());exit;
        //设计节点

        if($info['node_id']== 6 && $processInfo['id'] == 10){//预算

            $info_action = CustomerBudgetModel::where('id',$info['action_table_id'])->find();

            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['budget_status'=>0, 'budget_id'=>$info_action['id']]);

            $CustomerAuthModel = new CustomerAuthModel;
            $CustomerAuthModel->relationCustomer(['customer_id'=>$info['customer_id'], 'admin_id'=>$info_action['admin_id'], 'audit_admin_id'=>$info['audit_admin_id']]);


        }elseif ($info['node_id'] == 7 && $processInfo['id'] == 11){//量房

            $info_action = CustomerRulerModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['design_status'=>0, 'ruler_id'=>$info_action['id']]);
            $CustomerAuthModel = new CustomerAuthModel;
            $CustomerAuthModel->relationCustomer(['customer_id'=>$info['customer_id'], 'admin_id'=>$info_action['admin_id'], 'audit_admin_id'=>$info['audit_admin_id']]);


        }elseif ($info['node_id'] == 8 && $processInfo['id'] == 12){//图纸审核

            $info_action = CustomerDrawModel::where('id',$info['action_table_id'])->find();
            //审核通过把id回写
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['design_status'=>3]);


        }elseif ($info['node_id'] == 9 && $processInfo['id'] == 15){//合同-总经理

            $info_action = CustomerContractModel::where('id',$info['action_table_id'])->find();
            if($info_action){
                CustomerModel::where('id',$info['customer_id'])->inc('order_total_amount', $info_action['final_price'])->update();
                CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['contract_id'=>$info['action_table_id'] ,'order_status'=> 0,'budget_status'=>4]);//已签合同
            }


        }elseif($info['node_id'] == 10 && $processInfo['id'] == 17){//放弃品类-总经理

            $info_action = CustomerGoodsDesertModel::where('id',$info['action_table_id'])->find();


            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['status'=>0]);

        }elseif($info['node_id'] == 11 && $processInfo['id'] == 18){//收款-会计

            $customer_payment = CustomerPaymentModel::where('id',$info['action_table_id'])->value('customer_payment');
            CustomerModel::where('id',$info['customer_id'])->inc('payment_amount',$customer_payment)->update();
        }elseif($info['node_id'] == 12 && $processInfo['id'] == 21){//退款-总经理
            $customer_payment = CustomerPaymentModel::where('id',$info['action_table_id'])->value('customer_payment');
            CustomerModel::where('id',$info['customer_id'])->dec('payment_amount',$customer_payment)->update();
        }elseif($info['node_id'] == 13 && $processInfo['id'] == 22){//放弃客户-部门经理

            CustomerModel::where('id',$info['customer_id'])->update(['customer_status'=>0]);//已放弃
        }elseif($info['node_id'] == 13 && $processInfo['id'] == 23){//放弃客户-总经理

            CustomerModel::where('id',$info['customer_id'])->update(['customer_status'=>-1]);//已放弃
        }elseif($info['node_id'] == 14 && $processInfo['id'] == 24){//申请售后-支付经理

            $info_action = SaleAfterModel::where('id',$info['action_table_id'])->find();

            $CustomerAuthModel = new CustomerAuthModel;
            $CustomerAuthModel->relationCustomer(['customer_id'=>$info['customer_id'], 'admin_id'=>$info_action['sale_admin_id'], 'audit_admin_id'=>$info['audit_admin_id']]);
        } elseif($info['node_id'] == 15 && $processInfo['id'] == 25){//完成售后-售后申请人


        } elseif($info['node_id'] == 15 && $processInfo['id'] == 34){//完成售后-会计


        }
        elseif($info['node_id'] == 16 && $processInfo['id'] == 26){//待下单
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>0.2]);//采购审核通过
        }
        elseif($info['node_id'] == 16 && $processInfo['id'] == 27){//待下单
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>1]);// 设计主管审核通过
        }
        elseif($info['node_id'] == 17 && $processInfo['id'] == 28){//订单复核
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>2.1]);//设计师审核通过
        }elseif($info['node_id'] == 17 && $processInfo['id'] == 29){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>2.2]);//客户经理通过
        }elseif($info['node_id'] == 17 && $processInfo['id'] == 30){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>2.3]);//交付经理通过
        }
        elseif($info['node_id'] == 17 && $processInfo['id'] == 35){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3]);//设计主管通过
            //任务通知
            //$this->taskModel->sendTaskInfo($dataTask['receive_admin_id'],$nodeProcess['process_name']);
        }
        elseif($info['node_id'] == 18 && $processInfo['id'] == 31){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.2]);//会计审核通过
        }elseif($info['node_id'] == 18 && $processInfo['id'] == 32){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.3]);//总经理审核通过
        }

        elseif($info['node_id'] == 18 && $processInfo['id'] == 33){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>4]);//管理员审核通过
        }

        elseif($info['node_id'] == 19 && $processInfo['id'] == 36){//补材料
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>0.2]);//客户代表通过
        }elseif($info['node_id'] == 19 && $processInfo['id'] == 37){//补材料
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3]);//交付经理审核通过
        }
        elseif($info['node_id'] == 20 && $processInfo['id'] == 38){//美容
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.1]);//交付经理审核通过
        }elseif($info['node_id'] == 22 && $processInfo['id'] == 39){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.2]);//会计审核通过
        }elseif($info['node_id'] == 22 && $processInfo['id'] == 40){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.3]);//总经理审核通过
        }

        elseif($info['node_id'] == 22 && $processInfo['id'] == 41){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>5]);//管理员审核通过
        }

        elseif($info['node_id'] == 21 && $processInfo['id'] == 42){//安装
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.1]);//交付经理审核通过
        }elseif($info['node_id'] == 23 && $processInfo['id'] == 43){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.2]);//会计审核通过
        }elseif($info['node_id'] == 23 && $processInfo['id'] == 44){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>3.3]);//总经理审核通过
        }

        elseif($info['node_id'] == 23 && $processInfo['id'] == 45){
            $info_action = OrderModel::where('id',$info['action_table_id'])->find();
            CustomerGoodsDataModel::where('id',$info_action['goods_data_id'])->update(['order_status'=>5]);//管理员审核通过
        }


    }

    //公共调用添加任务
    public function commonAddTask($data){
//        $data = $this->request->param();
        $nodeInfo = NodeModel::where('id',$data['node_id'])->find();

        if(empty($nodeInfo)) exception('任务配置已被修改');
        if($nodeInfo['node_type']==0){

            if(empty($data['receive_admin_id'])) exception('请指定任务执行人');
            $receiveAdminId = $data['receive_admin_id'];
        }

        if($nodeInfo['node_type']==1){
            $authInfo = CustomerAuthModel::where('customer_id',$data['customer_id'])->where('node_id',$data['node_id'])->find();
            if(empty($authInfo)) exception('当前任务尚未指定执行人');
            $receiveAdminId = $authInfo['admin_id'];
        }
        if($nodeInfo['node_type']==2){
            $authInfo = CustomerAuthModel::where('order_id',$data['order_id'])->where('node_id',$data['node_id'])->find();
            if(empty($authInfo)) exception('当前任务尚未指定执行人');
            $receiveAdminId = $authInfo['admin_id'];
        }

        //todo 验证登录人执行权限
        $info = $this->addNewTask($data['customer_id'],0,$data['node_id'],$data['process_id'],$receiveAdminId,$data['admin_id'],$data['action_table_id']);
        return $info;
    }

    function adminInfoData(){
        return $this->belongsTo('app\common\model\AdminModel','admin_id','id');
    }
    function customerInfoData(){
        return $this->belongsTo('app\common\model\worker\CustomerModel','customer_id','id');
    }
    //任务创建通知
    public function sendTaskInfo($receive_admin_id,$process_name){

        //todo 发送订阅消息
        $receiveInfo = AdminModel::where('id',$receive_admin_id)->find();//->where('openid','<>','')
        if($receiveInfo && $receiveInfo['openid']){
            $message = [
                'openid' =>$receiveInfo['openid'],     // 接收者（用户）的 openid
                //'page' => '/pages/task/index',
                'msg' => [
                    'thing9' => [
                        'value' => '收到新任务',
                    ],
                    'time3' => [
                        'value' => date('Y-m-d H:i'),
                    ],
                    'time7' => [
                        'value' => date('Y-m-d H:i'),
                    ],
                    'time8' => [
                        'value' => date('Y-m-d H:i:s',strtotime('+1 day')), //截至时间， 当前时间加一天
                    ],
                    'thing4' => [
                        'value' => $process_name,
                    ],
                ],
            ];
            $res = sendMiniMessage($message);
            //var_dump($res);exit;
        }


    }
    //审核通知auditCustomTask
    public function  sendAuditTask($data){

        $info = TaskModel::where('id',$data['id'])->find();
        //todo 给任务执行人和任务发起人发送消息
        $auditMsg = $data['audit_status']==1?'任务已审核':'任务已驳回';

        $sendAdmin = AdminModel::where('id',$info['admin_id'])->find();
        $message = [
            //'page' => '/pages/task/custom_task_info?task_id='.$info['id'],
            'msg' => [
                'thing9' => [
                    'value' => $auditMsg,
                ],
                'time3' => [
                    'value' => date('Y-m-d H:i'),
                ],
                'time7' => [
                    'value' => $info['audit_time'],
                ],
                'time8' => [
                    'value' => date('Y-m-d H:i'),
                ],
                'thing4' => [
                    'value' => $info['node_name'],
                ],
            ],
        ];
        if(!empty($sendAdmin['openid'])){
            $message['openid'] = $sendAdmin['openid'];
            $res = sendMiniMessage($message);

        }
        $receiveAdmin = AdminModel::where('id',$info['receive_admin_id'])->find();
        if(!empty($receiveAdmin['openid'])){
            $message['openid'] = $receiveAdmin['openid'];
            $res = sendMiniMessage($message);

        }

    }

}
